<template>
  <a-drawer
    :title="title"
    :closable="false"
    :maskClosable="false"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="开课学年" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input :value="selectedCoursePublish.schoolYearName" disabled/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="开课学期" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input :value="selectedCoursePublish.termName" disabled/>
            </a-form-item
            >
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="开课课程" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                :disabled="readOnly || id === undefined"
                show-search
                allowClear
                placeholder="请选择开课课程"
                v-decorator="['coursePublishId', { rules: [{ required: true, message: '请选择开课课程' }] }]"
                @change="changeCoursePublish"
              >
                <a-select-option v-for="item of this.coursePublishList" :key="item.id">
                  {{ item.courseName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="实验模块" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                :disabled="readOnly"
                show-search
                allowClear
                placeholder="请选择实验模块"
                v-decorator="['moduleId']">
                <a-select-option v-for="item of this.moduleList" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-item label="实验项目" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                :disabled="readOnly"
                show-search
                allowClear
                placeholder="请选择实验项目"
                v-decorator="['projectId', { rules: [{ required: true, message: '请选择实验项目' }] }]"
              >
                <a-select-option v-for="item of this.projectList" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-item label="排课轮次" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-tag color="red" v-if="!this.form.getFieldValue('coursePublishId')">请先选择开课课程</a-tag>
              <div v-else>
                <a-checkbox-group v-model="selectedFrequencyIndex">
                  <div
                    class="frequency-items"
                    v-for="(frequencyItem, index) in coursePublishFrequencyList"
                    :key="frequencyItem.id">
                    <a-checkbox :value="index" disabled>
                      {{ frequencyItem.frequencyIndex }}轮({{ frequencyItem.weekStart }}-{{ frequencyItem.weekEnd }}周)
                    </a-checkbox>
                    <div class="dayOfWeek-items" v-if="frequencyItem.dayOfWeek">
                      <div class="brackets">(</div>
                      <a-checkbox-group v-model="selectedDayOfWeekArray[index]">
                        <a-checkbox
                          :disabled="readOnly"
                          v-for="(dayOfWeekItem, idx) in frequencyItem.dayOfWeek.split(',').sort().map((item) => parseInt(item))"
                          :key="idx"
                          :value="dayOfWeekItem">
                          周{{ ['一', '二', '三', '四', '五'][dayOfWeekItem - 1] }}
                        </a-checkbox>
                      </a-checkbox-group>
                      <div class="brackets">)</div>
                    </div>
                  </div>
                </a-checkbox-group>
              </div>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="实验人数" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-tooltip placement="right" title="注：实验人数将用于学生选课人数限制">
                <a-input-number
                  :disabled="viewOnly"
                  :min="1"
                  v-decorator="['maxStudents']"
                />
              </a-tooltip>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="实验老师" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                :disabled="readOnly"
                show-search
                allowClear
                placeholder="请选择实验老师"
                v-decorator="['teacherId']"
              >
                <a-select-option v-for="item of this.teacherList" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="实验教室" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                :disabled="readOnly"
                show-search
                :filter-option="(input, option) => option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                "
                allowClear
                placeholder="请选择实验教室"
                v-decorator="['classroomId']"
              >
                <a-select-option v-for="item of this.classroomList" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <div class="drawer-footer">
      <a-button class="left" @click="handleCancel">关闭</a-button>
      <a-button class="right" type="primary" @click="handleSubmit" :disabled="viewOnly">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
  import { courseScheduleAdd, courseScheduleEdit } from '@/api/modular/main/courseScheduleManage'
  import { coursePublishList } from '@/api/modular/main/coursePublishManage'
  import { coursePublishFrequencyList } from '@/api/modular/main/coursePublishFrequencyManage'
  import { courseScheduleFrequencyList } from '@/api/modular/main/courseScheduleFrequencyManage'
  import { moduleList } from '@/api/modular/system/moduleManage'
  import { projectList } from '@/api/modular/system/projectManage'
  import { getUserByType } from '@/api/modular/system/userManage'
  import { sysClassroomList } from '@/api/modular/system/sysClassroomManage'

  export default {
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        id: undefined,
        title: '',
        visible: false,
        viewOnly: false,
        confirmLoading: false,
        record: undefined,
        form: this.$form.createForm(this),
        coursePublishList: [],
        coursePublishFrequencyList: [],
        moduleList: [],
        projectList: [],
        teacherList: [],
        classroomList: [],

        selectedCoursePublish: {
          coursePublishId: undefined,
          schoolYearName: undefined,
          termName: undefined
        },

        selectedFrequencyIndex: [],
        selectedDayOfWeekArray: []
      }
    },
    computed: {
      readOnly() {
        return this.viewOnly || (this.record && this.record.state === 1)
      }
    },
    watch: {
      selectedDayOfWeekArray(val) {
        this.selectedFrequencyIndex = val.map((item, index) => {
          if (item.length > 0) return index
        })
      }
    },
    methods: {
      // 初始化方法
      open(record, viewOnly) {
        this.viewOnly = viewOnly
        // console.log(record)
        this.visible = true
        this.confirmLoading = true
        if (record) {
          // console.log(record.courseId)
          this.record = record
          this.id = record.id
          this.title = '编辑排课'
          this.loadCoursePublishList().then(() => {
            this.loadDataOfList(record.coursePublishId)

            this.form.setFieldsValue({
              id: record.id,
              coursePublishId: record.coursePublishId,
              collegeId: record.collegeId,
              courseId: record.courseId,
              schoolYearId: record.schoolYearId,
              termId: record.termId,
              teacherId: record.teacherId,
              moduleId: record.moduleId,
              maxStudents: record.maxStudents,
              classroomId: record.classroomId,
              projectId: record.projectId
            })

            // load course schedule frequency list
            courseScheduleFrequencyList({
              courseScheduleId: record.id
            }).then((res) => {
              if (res.success) {
                res.data.forEach((item) => {
                  this.selectedFrequencyIndex.push(item.frequencyIndex - 1)
                  this.selectedDayOfWeekArray[item.frequencyIndex - 1] = item.dayOfWeek
                    .split(',')
                    .map((item) => parseInt(item))
                })
              }
            })
            this.confirmLoading = false
          })
        }
      },
      openAndCreate(coursePublish) {
        this.id = undefined
        this.title = '新增排课'

        this.loadCoursePublishList().then(() => {
          this.selectedCoursePublish = {
            coursePublishId: coursePublish.id,
            schoolYearName: coursePublish.schoolYearName,
            termName: coursePublish.termName
          }

          this.form.setFieldsValue({
            coursePublishId: coursePublish.id
          })

          this.loadDataOfList(coursePublish.id)
        })
        this.visible = true
      },
      /**
       * 提交表单
       */
      handleSubmit() {
        const {
          form: { validateFields }
        } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            const appendParams = {
              coursePublishId: this.selectedCoursePublish.id, // set coursePulish ID
              frequencyList: this.selectedFrequencyIndex
                .filter((item) => item != null && item !== undefined)
                .map((item) => {
                  const cpfl = this.coursePublishFrequencyList[item]
                  return {
                    frequencyIndex: cpfl.frequencyIndex,
                    weekStart: cpfl.weekStart,
                    weekEnd: cpfl.weekEnd,
                    dayOfWeek: this.selectedDayOfWeekArray[item].join(',')
                  }
                }) // set frequency data
            }

            console.log(appendParams)

            for (const key in values) {
              if (typeof values[key] === 'object' && values[key] != null) {
                values[key] = JSON.stringify(values[key])
              }
            }
            values = {
              ...values,
              ...appendParams
            }
            // console.log(values)
            if (this.id) {
              values.id = this.id
              courseScheduleEdit(values)
                .then((res) => {
                  if (res.success) {
                    this.$message.success('更新成功')
                    this.confirmLoading = false
                    this.$emit('ok', values)
                    this.handleCancel()
                  } else {
                    this.$message.error('更新失败：' + res.message)
                  }
                })
                .finally((res) => {
                  this.confirmLoading = false
                })
            } else {
              courseScheduleAdd(values)
                .then((res) => {
                  if (res.success) {
                    this.$message.success('新增成功')
                    this.confirmLoading = false
                    this.$emit('ok', values)
                    this.handleCancel()
                  } else {
                    this.$message.error('新增失败') // + res.message
                  }
                })
                .finally((res) => {
                  this.confirmLoading = false
                })
            }
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel() {
        this.form.resetFields()
        this.visible = false
        this.viewOnly = false
        this.record = undefined
        this.selectedFrequencyIndex = []
        this.selectedDayOfWeekArray = []
      },
      loadCoursePublishList() {
        return new Promise((resolve, reject) => {
          coursePublishList().then((res) => {
            if (res.success) {
              this.coursePublishList = res.data
              resolve()
            }
          })
        })
      },
      loadModuleList(collegeId) {
        moduleList({
          collId: collegeId,
          status: this.id ? null : 0
        }).then((res) => {
          if (res.success) {
            this.moduleList = res.data
          }
        })
      },
      loadProjectList(collegeId) {
        projectList({
          collId: collegeId,
          status: this.id ? null : 0
        }).then((res) => {
          if (res.success) {
            this.projectList = res.data
          }
        })
      },
      loadTeacherList(collegeId) {
        getUserByType({
          userType: 'tch',
          collId: collegeId
        }).then((res) => {
          if (res.success) {
            this.teacherList = res.data
          }
        })
      },
      loadClassroomList(collegeId) {
        sysClassroomList({
          collId: collegeId
        }).then((res) => {
          if (res.success) {
            this.classroomList = res.data
          }
        })
      },
      loadCoursePublishFrequencyList(coursePublishId) {
        coursePublishFrequencyList({
          coursePublishId: coursePublishId
        }).then((res) => {
          if (res.success) {
            this.coursePublishFrequencyList = res.data
          }
        })
      },
      changeCoursePublish(coursePublishId) {
        this.loadDataOfList(coursePublishId)
        this.form.setFieldsValue({
          moduleId: undefined,
          projectId: undefined,
          teacherId: undefined,
          classroomId: undefined
        })
      },
      loadDataOfList(coursePublishId) {
        console.log('coursePublishId =', coursePublishId)
        this.coursePublishList.forEach((i) => {
          console.log(i.id)
        })
        const matched = this.coursePublishList.find((item) => item.id === coursePublishId)
        if (matched) {
          this.selectedCoursePublish = matched
          const collegeId = matched.collegeId
          this.loadModuleList(collegeId)
          this.loadProjectList(collegeId)
          this.loadTeacherList(collegeId)
          this.loadClassroomList(collegeId)
          this.loadCoursePublishFrequencyList(matched.id)
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .frequency-items {
    display: flex;
    align-items: center;
    width: 100%;

    .brackets {
      padding: 0 10px;
    }

    .dayOfWeek-items {
      display: flex;
    }
  }
</style>
